package cluster.traversal;

import text.Text;
import text.TextSetManager;
import text.traversal.ITextTraversal;

public class UpdateBestClasses implements ITextTraversal
{
	private final TextSetManager textSetManager;
	private final TextSetManager classManager;
	
	private int changeCount = 0;
	
	public int getChangeCount()
	{
		return this.changeCount;
	}
	
	public UpdateBestClasses(TextSetManager textSetManager, TextSetManager classManager)
	{
		this.textSetManager = textSetManager;
		this.classManager = classManager;
	}
	
	public void traversal(String word, Text text)
	{
		double bestDistance = Double.POSITIVE_INFINITY;
		Text bestClass = null;
				
		for(Text classText : this.classManager.getTextList())
		{
			double distance = 0;
			for(Text text3 : this.textSetManager.getTextList())
			{
				Double value = text3.getInfo(ComputeTFIDF.TFIDF, word);
				double tfidf1 = value!=null?value:0;
				
				String textTFIDFMean = ComputeMean.getInfoName(text3.getName(), ComputeTFIDF.TFIDF);
				value = classText.getInfo(textTFIDFMean);
				double tfidf2 = value!=null?value:0;

				distance += tfidf1 * tfidf2;
			}
			
			distance = 1 - distance;
			
			if(distance < bestDistance)
			{
				bestDistance = distance;
				bestClass = classText;
			}
		}
		
		for(Text classText : this.classManager.getTextList())
		{
			if(classText.removeWord(word))
			{
				if(!bestClass.equals(classText))
				{
					//System.out.println(word + " (" + bestDistance + ") " + text2.getName() + " -> " + bestClass.getName());
					changeCount++;
				}
				break;
			}
		}
		
		bestClass.addWord(word);
	}
}
